import { VALIDATE_FAILED, getRefPromise, validateFormAndTables, validateFormModelAndTables } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { httpAction, getAction } from '@/api/manage'
import { queryMaterialVoInfoById, readFile, getbillcodebyobject } from '@/api/erp/commonapi'
import { handleValueChange, handleJvxeValueChange } from '@/utils/erputils/erpcommonutils';
import { ACCESS_TOKEN, TENANT_ID } from "@/store/mutation-types"
import { getNowFormatDate } from '@/utils/util'
// import { validateDuplicateValue, getNowFormatDate } from '@/utils/util'
import { FormTypes } from '@/utils/JEditableTableUtil'
import * as XLSX from 'xlsx'
import { deleteAction, postAction } from '../api/manage';
import { computed, onBeforeUpdate, onMounted, onUpdated } from 'vue';


// import { create } from 'tinymce';

export const JVxeTableModelMixin = {
  data () {
    return {
      inputVisible: false,
      title: '操作',
      changereasonvisble: false,
      visible: false,
      confirmLoading: false,
      searchMaterialCode: '',
      scrolling: true,
      formstatus: '0',//0新增，1显示 2编辑 3审批
      model: {},
      addbuttonstate: false,
      canclebuttonstate: false,
      savebuttonstate: false,
      referbuttonstate: false,
      submitbuttonstate: false,
      deletebuttonstate: false,
      changebuttonstate: false,
      editbuttonstate: false,
      printbuttonstate: false,
      auditbuttonstate: false,
      tonextbuttonstate: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 }
      }
    }
  },
  watch: {
    $router: function (to, from) {
      let fromparams = from.params;
      let toparams = to.params;
      console.log("fromparams" + JSON.stringify(fromparams));
      // if (fromparams != toparams) {
      //   created();
      // }
      created();
    },
    'formstatus': {
      handler (val) {
        this.setButtonState();
      }
    }
  },
  activated () {
    // 路由更新时调用，例如参数或查询变化
    // console.log("activated");


    setTimeout(() => {
      this.getCurrentData();
    }, 1000);

    // if (this.model.id != undefined) {
    //   this.edit(this.model);

    // }
    setTimeout(() => {
      this.setButtonState()
    }, 1000);

    // next();
  },

  onUpdated () {
    this.setButtonState();
  },

  async created () {

    console.log("minxin created");
    if (!this.model.id) {
      this.model.billdate = getNowFormatDate();
      let currentuser = this.$store.getters.userInfo
      this.model.companyid = localStorage.getItem(currentuser.id + '_list_companyid');
      this.formstatus = "0";

    } else {

    }

    // this.getCurrentData();

    let params1 = {
      objectcode: this.maincusObject,
    }

    let res = await getAction("/base/scmcustomfields/getcustomfieldsbyobjectcode", params1);
    if (res.success) {
      let cusret = res.result;
      this.maincusList = cusret;
      for (let i = 0; i < cusret.length; i++) {
        if (this.model.id) {
          //不是新增，则进行赋值
          this.$set(this.maincusItems, cusret[i]["customcode"], this.model[cusret[i]["customcode"]])
        } else {
          this.$set(this.maincusItems, cusret[i]["customcode"], "");
        }
      }

      // console.log("get the mainmodelifno....--->" + JSON.stringify(this.maincusItems));
    }

    if (!this.model.id) {
      // this.add();
      this.disabled = true;
    } else {
      this.edit(this.model);
    }

    this.requestTableCustomCode();


  },

  async onMounted () {
    // let routeparams = this.$route.params;

    console.log(this.$route);

    if (this.$route.hasOwnProperty("query") && this.$route.query != null && this.$route.query != undefined && Object.keys(this.$route.query).length != 0) {
      return;
    }

    if (this.$route.hasOwnProperty("params") && this.$route.params != null && this.$route.params != undefined && Object.keys(this.$route.params).length != 0) {
      return;
    }

    // if(this.$route.query !=null && this.$route.query != undefined){
    //   return;
    // }

    if (this.model.hasOwnProperty("id") && this.model.id != null && this.model.id != undefined) {
      return;
    }
    // this.add();

    // if (!this.model.id && (this.model.billcode != "" || this.model.billcode != undefined)) {
    //   //去获取单据编号，更新到当前单据上
    //   getbillcodebyobject({ objectcode: this.objectcode }).then(res => {
    //     if (res.success) {
    //       this.$set(this.model, "billcode", res.result);
    //     }
    //   })
    // }
  },
  async onBeforeUpdate () {
    // await this.requestTableCustomCode()
    if (this.model.hasOwnProperty("billcode")) {
      let nowbillcode = this.model.billcode;
      if (!(nowbillcode != null && nowbillcode != "" && nowbillcode != undefined)) {
        getbillcodebyobject({ objectcode: this.objectcode }).then(res => {
          if (res.success) {
            this.$set(this.model, "billcode", res.result);
          }
        })
      }
    } else {
      getbillcodebyobject({ objectcode: this.objectcode }).then(res => {
        if (res.success) {
          this.$set(this.model, "billcode", res.result);
        }
      })
    }

    // this.setButtonState();
    this.$forceUpdate();
  },
  methods: {
    handleClose (removedTag) {
      const tags = this.tags.filter(tag => tag !== removedTag);
      console.log(tags);
      this.tags = tags;
    },

    showInput () {
      this.inputVisible = true;
      this.$nextTick(function () {
        this.$refs.input.focus();
      });
    },

    handleInputChange (e) {
      this.inputValue = e.target.value;
    },

    handleInputConfirm () {
      const inputValue = this.inputValue;
      let tags = this.tags;
      if (inputValue && tags.indexOf(inputValue) === -1) {
        tags = [...tags, inputValue];
      }
      console.log(tags);
      Object.assign(this, {
        tags,
        inputVisible: false,
        inputValue: '',
      });
    },
    generateItemSysformat () {
      if (this.itemcusObject == undefined || this.itemcusObject == "") {
        return;
      }
      //todo  获取当前行的column 组织生成对应的data
      if (this.refKeys.length == 0) {
        return;
      }
      let subtablename = this.refKeys[0] + "Table";
      let newColumns = this[subtablename].columns;

      postAction("/base/scmcustomformat/generatecustomformat", { 'itemobjectcode': this.itemcusObject, columns: newColumns }).then(res => {
        if (res.success) {
          this.$message.success("导入系统成功，如已导入不需继续导入");
        }
      })
    },

    /**进行审批操作 */
    handleAudit (record, datacode, djtype) {
      if (record.status === '1') {
        this.$message.error("单据正在审批中不允许再次提交审批");
        return;
      } else if (record.status === '2') {
        this.$message.error("单据已审批通过不允许再次提交审批");
        return;
      }
      let url = "/flow/common/startprocess";
      let params = {
        dataid: record.id,
        datacode: datacode,
        djtype: djtype
      };
      getAction(url, params).then((res) => {
        if (res.success) {
          this.$message.success("流程发起成功");
          let params = { id: record.id }
          //获取主表信息
          this.getMainData(this.url.querybyId || this.url.queryById, params);
        } else {
          this.$message.error(res.message);
        }
      })
    },
    setButtonState () {
      this.addbuttonstate = !(this.formstatus == '0');
      this.canclebuttonstate = !(this.formstatus == '2');
      this.referbuttonstate = !(this.formstatus == '2')
      this.savebuttonstate = !(this.formstatus == '2' && (this.model.status == '0' || this.model.status == undefined || this.model.status == '2' || this.model.status == '3'));
      this.submitbuttonstate = !((this.model.status == '0' || this.model.status == undefined) && this.model.id != undefined);
      this.deletebuttonstate = !((this.model.status == '0' || this.model.status == undefined) && this.model.id != undefined);
      this.changebuttonstate = !(this.model.status == '2')
      this.editbuttonstate = !((this.model.status == '0' || this.model.status == undefined) && this.model.id != undefined);
      this.printbuttonstate = !(this.model.status == '2')
      this.auditbuttonstate = !(this.model.status == '1')
      this.tonextbuttonstate = !(this.model.status == '2');

      // Vue.nextTick(() => {
      //   this.$forceUpdate();
      // })
    },
    async getCurrentData () {
      console.log("getcurrentdata");
      let routeparams = this.$route.params
      let routequery = this.$route.query;

      if (routeparams != undefined && (routeparams.id != '' && routeparams.id != undefined)) {
        let params = { id: routeparams.id }
        //获取主表信息
        await this.getMainData(this.url.querybyId || this.url.queryById, params);

        if (this.refKeys != null && this.refKeys.length > 0) {
          for (let i = 0; i < this.refKeys.length; i++) {
            let subtable = this.refKeys[i];
            let subtablename = this.refKeys[i] + "Table";
            //获取分录信息
            await this.requestSubTableData(this.url[subtable].list, params, this[subtablename])
            if (routeparams.disableSubmit != null && routeparams.disableSubmit != undefined) {
              this.disabled = routeparams.disableSubmit
              this.auditvisable = false;
            } else {
              this.disabled = true;
              this.auditvisable = true;
              this.audittaskid = routeparams.taskId;
            }
          }

        }
        this.edit(this.model);
        return;
      } else if (routequery != undefined && routequery.hasOwnProperty("fromtype")) {
        //  this.add();
        this.formstatus = '2'
        this.disabled = false;

        return;
      }

      if (!this.model.hasOwnProperty("id")) {
        // this.add();
        // this.disabled = true;
      } else {
        let id = this.model.id;
        if (id == undefined || id == "") {
          // this.add();
          // this.disabled = true;
        }
      }

      // this.setButtonState();

      // this.$forceUpdate();
    },
    handleAdd () {
      this.add();
    },
    handleImportExcel (info) {
      this.loading = true;
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        this.loading = false;
        if (info.file.response.success) {
          // this.$message.success(`${info.file.name} 文件上传成功`);
          if (info.file.response.code === 201) {
            let { message, result: { msg, fileUrl, fileName } } = info.file.response
            let href = window._CONFIG['domianURL'] + fileUrl
            this.$warning({
              title: message,
              content: (<div>
                <span>{msg}</span><br />
                <span>具体详情请 <a href={href} target="_blank" download={fileName}>点击下载</a> </span>
              </div>
              )
            })
          } else {
            this.$message.success(info.file.response.message || `${info.file.name} 文件上传成功`)
          }
          // this.loadData()
        } else {
          this.$message.error(`${info.file.name} ${info.file.response.message}.`);
        }
      } else if (info.file.status === 'error') {
        this.loading = false;
        if (info.file.response.status === 500) {
          let data = info.file.response
          const token = Vue.ls.get(ACCESS_TOKEN)
          if (token && data.message.includes("Token失效")) {
            this.$error({
              title: '登录已过期',
              content: '很抱歉，登录已过期，请重新登录',
              okText: '重新登录',
              mask: false,
              onOk: () => {
                store.dispatch('Logout').then(() => {
                  Vue.ls.remove(ACCESS_TOKEN)
                  window.location.reload();
                })
              }
            })
          }
        } else {
          this.$message.error(`文件上传失败: ${info.file.msg} `);
        }
      }
    },

    /**
     * 导出模板
     * @param {要导出的模板数据} data 
     */
    exportDataEvent (data) {
      const ws = XLSX.utils.aoa_to_sheet(data);
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
      XLSX.writeFile(wb, 'import.xlsx');
    },
    /**
     * 导入处理
     * @param {*} event 
     */
    async importDataEvent (event) {
      // 读取文件
      let dataBinary = await readFile(event.file)
      let workBook = XLSX.read(dataBinary, { type: 'binary', cellDates: true })
      let workSheet = workBook.Sheets[workBook.SheetNames[0]]
      const data = XLSX.utils.sheet_to_json(workSheet)

      let itemKey = this.refKeys[0];
      let curItemTable = this.$refs[itemKey];
      let columns = curItemTable.columns;

      for (let i = 0; i < data.length; i++) {
        let curObject = data[i];
        let newRow = {};
        for (var key in curObject) {
          for (let j = 0; j < columns.length; i++) {
            let curCol = columns[j]
            if (curCol.title === key) {
              // let curKey = curCol.key
              this.$set(newRow, curCol.key, curObject[key]);
              break;
            }
          }
        }
        curItemTable.dataSource.push(newRow);
      }
    },
    async insertMaterialCode (event, materialtype) {
      // console.log(event);
      let keyevent = event.$event;
      if (keyevent) {
        if (keyevent.keyCode === 13) {
          //结束
          console.log(event.value);
          let materialcode = event.value;
          //获取物料信息，新增行到当前页面上
          let itemKey = this.refKeys[0];

          let materialinfo = await queryMaterialVoInfoById({ materialid: materialcode });
          if (materialinfo.success) {
            let mat = materialinfo.result;
            if (mat) {
              let uomid = ''
              let curItemTable = this.$refs[itemKey];
              let columns = curItemTable.columns;
              for (let j = 0; j < columns.length; j++) {
                if (columns[j].key === 'materialid') {
                  let props = columns[j].props;
                  if (props.hasOwnProperty("materialtype")) {
                    let curMaterialType = props.materialtype;
                    if (curMaterialType == '0') {
                      //采购
                      uomid = mat.pouomid
                    } else if (curMaterialType == '1') {
                      uomid = mat.saleuomid
                    } else if (curMaterialType == '2') {
                      uomid = mat.stockuomid
                    }
                  }
                  break;
                }
              }
              let rows = {
                materialid: mat.id,
                materialcode: mat.materialcode,
                materialname: mat.materialname,
                qty: 1,
                uomid: uomid,
                model: mat.model,
                specs: mat.mspecs,
                taxinprice: mat.saleprice,
                taxrate: mat.taxrate,
              }
              let tableData = curItemTable.getAll().tableData;
              if (tableData.length == 0) {
                curItemTable.addRows(rows, false);
                this.searchMaterialCode = '';
                // curItemTable.dataSource = curItemTable.getAll().tableData;
                return;
              }
              let isHave = false;
              for (let i = 0; i < tableData.length; i++) {
                let curMat = tableData[i];
                if (curMat.materialid == mat.id) {
                  isHave = true;
                  let newQty = curMat.qty + 1;
                  this.$set(curMat, 'qty', newQty);
                  this.$set(curMat, 'taxinvalue', parseFloat(curMat.taxinprice) * newQty);
                }
              }
              if (isHave === false) {
                curItemTable.addRows(rows, false);
              } else {
                curItemTable.loadData(tableData)
                curItemTable.handleTableData()
                curItemTable.updateFooter()
                curItemTable.updateCache()
                curItemTable.checkSelectionStatus()
              }
            }
          }

          this.searchMaterialCode = '';
        }
      }

    },
    handleValueChange (event) {
      handleJvxeValueChange(event)
    },
    async getMainData (url, params) {

      let __that = this;
      let res = await getAction(url, params);
      if (res.success) {
        if (res.result instanceof Array) {
          __that.model = res.result[0];
        } else {
          __that.model = res.result;
        }
        // this.model=res.result || res.result[0]
      }
    },

    /** 获取所有的JVxeTable实例 */
    getAllTable () {
      if (!(this.refKeys instanceof Array)) {
        throw this.throwNotArray('refKeys')
      }
      let values = this.refKeys.map(key => getRefPromise(this, key))
      return Promise.all(values)
    },

    /** 遍历所有的JVxeTable实例 */
    eachAllTable (callback) {
      // 开始遍历
      this.getAllTable().then(tables => {
        // console.log("tables", tables)
        tables.forEach((item, index) => {
          if (typeof callback === 'function') {
            callback(item, index)
          }
        })
      })
    },

    /** 当点击新增按钮时调用此方法 */
    add () {
      this.model = {};
      this.$set(this.model, "billdate", getNowFormatDate());
      if (this.model.hasOwnProperty("billcode")) {
        let nowbillcode = this.model.billcode;
        if (!(nowbillcode != null && nowbillcode != "" && nowbillcode != undefined)) {
          getbillcodebyobject({ objectcode: this.objectcode }).then(res => {
            if (res.success) {
              this.$set(this.model, "billcode", res.result);
            }
          })
        }
      } else {
        getbillcodebyobject({ objectcode: this.objectcode }).then(res => {
          if (res.success) {
            this.$set(this.model, "billcode", res.result);
          }
        })
      }

      if (typeof this.addBefore === 'function') this.addBefore()
      // 默认新增空数据
      let rowNum = this.addDefaultRowNum
      if (typeof rowNum !== 'number') {
        rowNum = 1
        console.warn('由于你没有在 data 中定义 addDefaultRowNum 或 addDefaultRowNum 不是数字，所以默认添加一条空数据，如果不想默认添加空数据，请将定义 addDefaultRowNum 为 0')
      }

      if (this.refKeys != undefined) {
        this.eachAllTable((item) => {
          //update-begin-author:taoyan date:20210315 for: 一对多jvex 默认几行不好使了 LOWCOD-1349
          setTimeout(() => {
            item.addRows()
          }, 300)
          //update-end-author:taoyan date:20210315 for: 一对多jvex 默认几行不好使了 LOWCOD-1349
        })
      }
      if (typeof this.addAfter === 'function') this.addAfter(this.model)

      let params = {
        objectcode: this.maincusObject,
      }
      getAction("/base/scmcustomfields/getcustomfieldsbyobjectcode", params).then(res => {
        if (res.success) {
          let cusret = res.result;
          this.maincusList = cusret;
          for (let i = 0; i < cusret.length; i++) {
            this.$set(this.maincusItems, cusret[i]["customcode"], "");
          }

          console.log("get the mainmodelifno....--->" + JSON.stringify(this.maincusItems));
        }
      })
      //获取分录自定义字段
      let itemParams = {
        objectcode: this.itemcusObject,
      }
      // this.requestTableCustomCode("/base/scmcustomfields/getcustomfieldsbyobjectcode", itemParams, this.itemTable);
      this.requestTableCustomCode();
      this.edit(this.model)
      this.formstatus = '2'
      this.disabled = false;
    },

    async requestTableCustomCode () {

      let url = "/base/scmcustomfields/getcustomfieldsbyobjectcode";
      //获取分录自定义字段
      let params = {
        objectcode: this.itemcusObject,
      }
      let tab = this.itemTable;
      if (tab) {
        // tab.loading = true
        //获取自定义的格式信息
        let customformaturl = "/base/scmcustomformat/getcolumnlist";
        let __that = this;
        let res = await getAction(customformaturl, params);
        if (res.success) {
          const cusret = res.result;
          console.log("columns:" + JSON.stringify(cusret));
          let newColumns = [];
          let oldColumns = tab.columns;
          for (let i = 0; i < cusret.length; i++) {
            let currentitemtype = cusret[i]
            var filtecolumn = oldColumns.filter(x => x.key === currentitemtype.colid);
            if (filtecolumn.length > 0) {

              this.$set(filtecolumn[0], "title", currentitemtype.colname);
              if (currentitemtype.colwidth != null) {
                this.$set(filtecolumn[0], "width", currentitemtype.colwidth);
              }
              if (currentitemtype.colvisable === 'false') {
                this.$set(filtecolumn[0], "type", FormTypes.hidden);
                newColumns.push(filtecolumn[0]);
                continue;
              }

              if (currentitemtype.onlyread === 'true') {
                this.$set(filtecolumn[0], 'disabled', "true")
              }
              newColumns.push(filtecolumn[0]);
            } else {
              let newColumn = {
                title: currentitemtype.colname,
                key: currentitemtype.colid,
                width: currentitemtype.colwidth,
                type: FormTypes.input,
                placeholder: '请输入${title}',
                defaultValue: '',
              }
              if (currentitemtype.colvisable === 'false') {
                this.$set(newColumn, "type", FormTypes.hidden);
                newColumns.push(newColumn);
                continue;
              }

              if (currentitemtype.onlyread === 'true') {
                this.$set(newColumn, 'disabled', "true")
              }
              newColumns.push(newColumn);
            }
            // let newColumn = {
            //   title: currentitemtype.colname,
            //   key: currentitemtype.colid,
            //   width: currentitemtype.colwidth,
            //   placeholder: '请输入${title}',
            //   defaultValue: '',
            // }


            // if (currentitemtype.formtype === 'sel_material') {
            //   this.$set(newColumn, 'type', FormTypes.sel_material);
            // } else if (currentitemtype.formtype === 'input') {
            //   this.$set(newColumn, 'type', FormTypes.input);
            // } else if (currentitemtype.formtype === 'input_number') {
            //   this.$set(newColumn, 'type', FormTypes.inputNumber)
            // } else if (currentitemtype.formtype === 'date') {
            //   this.$set(newColumn, 'type', FormTypes.date)
            // } else if (currentitemtype.formtype === 'sel_vendor') {
            //   this.$set(newColumn, 'type', FormTypes.sel_vendor)
            // } else if (currentitemtype.formtype === 'search') {
            //   this.$set(newColumn, 'type', FormTypes.sel_search)
            //   this.$set(newColumn, 'dictCode', currentitemtype.coldict)
            // }

          }

          // tab.columns = newColumns;
          // tab.loadColumn(newColumns);

          // __that.$refs[__that.refKeys[0]].loadColumn(newColumns);
          // tab.columns = newColumns;
          this.$set(tab, "columns", newColumns);
          // tab.loading = false;
        }
        let res1 = await getAction(url, params);
        const cusret = res1.result;
        let origcolumn = tab.columns;
        if (cusret) {
          for (let i = 0; i < cusret.length; i++) {
            let curItem = cusret[i];
            let newColumn = {
              title: curItem.customname,
              key: curItem.customcode,
              type: FormTypes.input,
              width: "100px",
              placeholder: '请输入${title}',
              defaultValue: '',
            }
            var result = origcolumn.some(item => {
              if (item.key === curItem.customcode) {
                return true
              }
            })
            if (!result) {
              origcolumn.push(newColumn);
            }
          }
        }
        //  tab.columns = [...origcolumn];
        // tab.setColumns(origcolumn);
        // tab.loading = false;

        //  let curItemTable = this.$refs[this.activeKey]
        // curItemTable.columns = [...origcolumn];
        // curItemTable.updateCache();

        this.$set(tab, 'columns', [...origcolumn]);
        this.$forceUpdate();

      }
    },
    /** 当点击了编辑（修改）按钮时调用此方法 */
    async edit (record) {
      if (typeof this.editBefore === 'function') this.editBefore(record)
      this.visible = true
      if (this.refKeys != null && this.refKeys.length > 0) {
        this.activeKey = this.refKeys[0]
        // this.$refs.form.resetFields()
        // this.model = Object.assign({}, record)
        if (record.hasOwnProperty("id")) {
          this.getMainData(this.url.querybyId || this.url.queryById, { id: record.id });
          this.model.id = record.id;
        } else {
          this.model = Object.assign({}, record)
        }
        if (this.model.companyid === null || this.model.companyid === undefined ||
          this.model.companyid === '') {
          let currentuser = this.$store.getters.userInfo
          this.model.companyid = localStorage.getItem(currentuser.id + '_list_companyid');
        }
        //增加对自定义字段的处理
        let params = {
          objectcode: this.maincusObject,
        }
        getAction("/base/scmcustomfields/getcustomfieldsbyobjectcode", params).then(res => {
          if (res.success) {
            let cusret = res.result;
            this.maincusList = cusret;
            for (let i = 0; i < cusret.length; i++) {
              this.$set(this.maincusItems, cusret[i]["customcode"], record[cusret[i]["customcode"]]);
            }
          }
        })


        //await this.requestTableCustomCode();

        let subtable = this.refKeys[0];
        let subtablename = this.refKeys[0] + "Table";

        let params1 = { id: record.id }

        //获取分录信息
        this.requestSubTableData(this.url[subtable].list, params1, this[subtablename])
      }

      if (typeof this.editAfter === 'function') this.editAfter(this.model)

      // this.setButtonState();


      this.formstatus = '2';
      this.disabled = false;

    },
    /** 关闭弹窗，并将所有JVxeTable实例回归到初始状态 */
    close () {
      this.visible = false
      this.eachAllTable((item) => {
        item._remove()
      })
      this.$emit('close')
    },

    /** 查询某个tab的数据 */
    async requestSubTableData (url, params, tab, success) {
      if (tab == undefined) {
        return;
      }
      tab.loading = true
      await getAction(url, params).then(res => {
        let { result } = res
        let dataSource = []
        if (result) {
          if (Array.isArray(result)) {
            dataSource = result
          } else if (Array.isArray(result.records)) {
            dataSource = result.records
          }
        }
        tab.dataSource = dataSource
        typeof success === 'function' ? success(res) : ''
      }).finally(() => {
        tab.loading = false
      })
    },
    /** 发起请求，自动判断是执行新增还是修改操作 */
    request (formData) {
      let url = this.url.add, method = 'post'
      if (this.model.id) {
        url = this.url.edit
        method = 'put'
      }
      this.confirmLoading = true
      console.log("formData===>", formData);
      let __that = this;
      httpAction(url, formData, method).then(async (res) => {
        if (res.success) {
          this.$message.success(res.message)
          if (res.result) {
            if (method == 'post') {
              __that.model.id = res.result;
            }

            let params = { id: __that.model.id }
            //获取主表信息
            __that.getMainData(__that.url.querybyId || __that.url.queryById, params);
          }
          __that.disabled = true;
          __that.formstatus = '0';
          this.$emit('ok')
          if (typeof this.afterSave === 'function') {
            this.afterSave(formData);
          }



          // this.close()
        } else {
          this.$message.error(res.message)
        }
      }).finally(() => {
        this.confirmLoading = false
      })
    },

    handleChange () {
      this.changereasonvisble = true;
      this.formstatus = '2';
      this.setButtonState();
    },

    /* --- handle 事件 --- */

    /** ATab 选项卡切换事件 */
    handleChangeTabs (key) {
      // 自动重置scrollTop状态，防止出现白屏
      getRefPromise(this, key).then(vxeTable => {
        vxeTable.resetScrollTop()

        if (typeof this.myafterchangetab == "function") {
          this.myafterchangetab(key)
        }
      })
    },
    /** 关闭按钮点击事件 */
    handleCancel () {
      // this.close()
      // this.$router.go(-1)
      // window.close();
      Vue.close();
    },
    /** 确定按钮点击事件 */
    handleOk () {
      /** 触发表单验证 */
      // console.log("getAlltable():"+JSON.stringify(this.getAllTable()));

      this.getAllTable().then(tables => {
        /** 一次性验证主表和所有的次表 */
        return validateFormModelAndTables(this.$refs.form, this.model, tables)
      }).then(allValues => {
        /** 一次性验证一对一的所有子表 */
        return this.validateSubForm(allValues)
      }).then(allValues => {
        if (typeof this.classifyIntoFormData !== 'function') {
          throw this.throwNotFunction('classifyIntoFormData')
        }

        if (allValues.tablesValue != undefined && allValues.tablesValue.length > 0) {
          let tabledata = allValues.tablesValue[0].tableData;
          if (tabledata.length > 0) {
            // tabledata.forEach(item => {
            //   if (item.hasOwnProperty("id")) {
            //     if (item.id.indexOf("row_") != -1) {
            //       delete item.id;
            //     }
            //   }
            // })
            for (var i = 0; i < tabledata.length; i++) {
              var item = tabledata[i];
              if (item.hasOwnProperty("id")) {
                if (item.id.indexOf("row_") != -1) {
                  item.id = "";
                }
              }
              if (item.hasOwnProperty("materialid")) {
                if (item.materialid == '' || item.materialid == undefined) {
                  tabledata.splice(i, 1);
                }
              }
            }
          }
        }


        let formData = this.classifyIntoFormData(allValues)
        if (formData == null) {
          return;
        }
        if (this.maincusItems != null && this.maincusItems != undefined) {
          const newformData = Object.assign(this.maincusItems, formData);
          return this.request(newformData)
        } else {
          return this.request(formData);
        }
      }).catch(e => {
        if (e.error === VALIDATE_FAILED) {
          // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
          this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
        } else {
          console.error(e)
        }
      })
    },
    //校验所有子表表单
    validateSubForm (allValues) {
      return new Promise((resolve) => {
        resolve(allValues)
      })
    },
    /* --- throw --- */

    /** not a function */
    throwNotFunction (name) {
      return `${name} 未定义或不是一个函数`
    },

    /** not a array */
    throwNotArray (name) {
      return `${name} 未定义或不是一个数组`
    },

    handleEdit () {
      if (this.model.hasOwnProperty("status")) {
        if (this.model.status == '2') {
          this.$message.error("当前单据已审批通过，不允许编辑");
          return;
        }
        if (this.model.status == '1') {
          this.$message.error("当前单据正在审批中，不允许编辑");
          return;
        }
      }
      this.disabled = false;
      this.formstatus = '2';

    },
    handleAddSubmit () {
      if (this.model.hasOwnProperty("id")) {
        if (this.model.status == "2") {
          this.$message.error("当前单据已审批通过，不允许提交！");
          return;
        }
        if (this.model.status == '1') {
          this.$message.error("当前单据已提交，不允许再次提交！");
          return;
        }

        if (this.model.hasOwnProperty("processinstance")) {

        }
        else {
          postAction(this.url.auditurl, { ids: this.model.id, flag: '1' }).then(res => {
            if (res.success) {
              this.$message.success("提交成功");
              let param = { id: this.model.id };
              this.getMainData(this.url.querybyId || this.url.queryById, param);
              this.formstatus = '0';
              this.model.status = '1';
              this.setButtonState();
            } else {
              this.$message.error(res.message);
            }
          })
        }
      }
    },
    handleDel () {
      if (this.model.hasOwnProperty("id")) {
        if (this.model.status == '2') {
          this.$message.error("当前单据已审批通过，不允许删除");
          return;
        }
        if (this.model.status == '1') {
          this.$message.error("当前单据正在审批中，不允许删除");
          return;
        }
        if (!this.url.delete) {
          this.$message.error("请设置url.delete属性!")
          return
        }
        var that = this;
        this.$confirm({
          title: '确实是否删除所选单据?',
          continue: '',
          onOk () {
            // that.loading = true;
            deleteAction(that.url.delete, { id: that.model.id }).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.add();
              } else {
                that.$message.warning(res.message);
              }
            }).finally(() => {
              // that.loading = false;
            });
          }
        })
      }
    },
    handleAddPost (flag) {
      if (this.model.hasOwnProperty("id")) {
        if (this.model.status == '0') {
          this.$message.error("当前单据未提交，不能审批！");
          return;
        }
        if (this.model.status == "2" && flag == "2") {
          this.$message.error("当前单据已审批通过，不允许再次审批！");
          return;
        }
        // if (this.model.status == '1') {
        //   this.$message.error("当前单据已提交，不允许再次提交！");
        //   return;
        // }
        postAction(this.url.auditurl, { ids: this.model.id, flag: flag.key }).then(res => {
          if (res.success) {
            if (flag.key == '2') {
              this.$message.success("审批通过");
              this.model.status = '2';
              this.setButtonState();
            } else if (flag.key == '3') {
              this.$message.success("审批不通过");
              this.model.status = '3';
              this.setButtonState();
            }
          } else {
            this.$message.error(res.message);
          }
        })
      }
    },
  }
}